import { reqOpenId, wxLogin } from '../api/auth'
import wxGetUserInfo from '../utils/wx-get-user-info.js'
export function getOpenId() {
  return new Promise((resolve, reject) => {
    // let openid = wx.getStorageSync('openid')
    // if (openid) {
    //   resolve(openid)
    //   return
    // }
    wx.login({
      async success(res) {
        if (res.code) {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          reqOpenId({ code: res.code }).then(({ openid }) => {
            wx.setStorageSync('openid', openid);
            resolve(openid)
          }).catch(e => {
            reject(e)
          })
        } else {
          reject(res.errMsg)
        }
      }
    })
  })
}

export async function loginUserInfo(wXUserInfo) {
  let openid = await getOpenId()
  let res = await wxLogin({
    openid,
    iv: wXUserInfo.iv,
    rawData: wXUserInfo.rawData,
    signature: wXUserInfo.signature,
    encryptedData: wXUserInfo.encryptedData
  }, { hasMessageError: false })

  wx.setStorageSync('access_token', res.token);
  return
}

export default async function login() {
  let wXUserInfo = await wxGetUserInfo()
  return loginUserInfo(wXUserInfo)
}